const request = require('request'),
    wechatApi = require('../config/config').wechatApi,
    db = require('../config/db');

/**
 * @author:ares
 * @datetime:2018/4/4 12:54
 * @description: 根据网页授权的access_token和openid拉取用户信息(获取用户授权时scope为 snsapi_userinfo)
 * @param {string} accessToken  网页授权的access_token
 * @param {string} openId       用户相对公众号的
 * @returns {Promise}
 */
function getUserInfo(accessToken, openId) {
    let openid = `&openid=${openId}`,
        options = {
            method: 'get',
            url: wechatApi.userinfoApiPrefix + accessToken + openid + wechatApi.userinfoApiSuffix
        };
    console.log('>> 获取用户信息地址 <<',options.url)
    return new Promise((resolve, reject) => {
        request(options, function (err, res, body) {
            if (res) {
                console.log('>> 用户信息 <<',body)
                let userinfo = JSON.parse(body),
                    updateInfo = db.buildUpdateStr('user_info',[
                    {field:'name',value:userinfo.nickname},
                    {field:'sex',value:userinfo.sex},
                    {field:'country',value:userinfo.country},
                    {field:'province',value:userinfo.province},
                    {field:'city',value:userinfo.city}
                ]);
                db.query(updateInfo).then(_rows => {
                    console.log('>> 更新用户信息 <<',_rows)
                    resolve(userinfo);
                }).catch(err => {
                    console.log('>> 更新用户信息错误 <<',err)
                    reject(err);
                });

            } else {
                reject(err);
            }
        });
    })
}

module.exports = getUserInfo;